package com.kgcx.organization.rabbitmq.consumer;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.constant.Cons;
import com.kgcx.common.rabbitmq.consts.QueueConst;
import com.kgcx.organization.domain.DriverMsg;
import com.kgcx.organization.domain.DriverMsgType;
import com.kgcx.organization.service.DriverMsgService;
import com.kgcx.organization.service.DriverService;

/**
 * 派车成功时 状态变更
 */
@Component
public class DriverOrderScheduleConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(DriverOrderScheduleConsumer.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverMsgService driverMsgService;

    @RabbitListener(queues = QueueConst.DRIVER_SCHEDULE_SUCCESS, errorHandler = "custRabbitListenerErrorHandler")
    @Transactional(rollbackFor = Exception.class)
    public void precessUserStatus(String json) {
        LOG.info("收到派单成功的MQ消息。\n" + json);

        ScheduleRecord scheduleRecord = JSONObject.parseObject(json, ScheduleRecord.class);
        if (null == scheduleRecord.getDriver_id()) {
            return;
        }

        addDriverMsg(scheduleRecord);

        driverService.updateDriverState(scheduleRecord.getDriver_id(), Cons.DRIVER_STATE_RUN, null, null,
                scheduleRecord.getAirport_id(), scheduleRecord.getStation_id());

        driverService.notifyDriverState(scheduleRecord.getDriver_id(), Cons.DRIVER_STATE_RUN);
    }

    private void addDriverMsg(ScheduleRecord scheduleRecord) {
        DriverMsg driverMsg = new DriverMsg();
        driverMsg.setIsRead(DriverMsg.UNREAD);
        driverMsg.setDriverId(scheduleRecord.getDriver_id());
        driverMsg.setTypeId(DriverMsgType.ORDER);
        driverMsg.setTitle("您有新的订单");
        driverMsg.setContent(
                "您有新的订单:订单号：[" + scheduleRecord.getOrder_no() + "]，从[" + scheduleRecord.getPlan_orig() + "]到["
                        + scheduleRecord.getPlan_dest() + "],请于[" + DateFormatUtils
                                .format(scheduleRecord.getPlan_depart_time(), Cons.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS)
                        + "]前到达接待。");
        driverMsgService.addDriverMsg(driverMsg);
    }

}

